/*
 * @Author: Robin 
 * @Date: 2017-10-10 18:05:15 
 * @Last Modified by: Robin
 * @Last Modified time: 2019-08-29 19:04:29
 */

let raven = require( 'raven' );
let log4js = require( 'log4js' );

let layouts = log4js.layouts;

let LEVEL_MAP = {
  debug: 'debug',
  info: 'info',
  warn: 'warning',
  error: 'error',
  fatal: 'fatal'
};
/**
 * appender function
 * @param {String} dsn 
 * @param {String} layout 
 * @param {String} level 
 */
function sentryAppender( dsn, layout, level, tags ) {

  let client = new raven.Client( dsn );

  layout = layout || layouts.messagePassThroughLayout;

  return function ( logEvent ) {

    // Check if the log level is enabled
    if( !level || logEvent.level.isGreaterThanOrEqualTo( level ) ) {

      // Format the log message
      let data = logEvent.data;
      let [ prefix, error ] = data;
      delete error.query.access_token;
      // let message = `${prefix} reported error of path: ${error.path}`
      let message = `${prefix} ${error.message}`;
      // Forward the message to Sentry
      client.captureMessage( message, {
        level: LEVEL_MAP[ logEvent.level.toString().toLowerCase() ],
        tags,
        extra: {
          path: error.path,
          message: error.message,
          params: error.params,
          query: error.query,
          method: error.method,
          stack: error.stack
        }
      } );

    }
  }
}


function configure( config ) {

  let layout;

  config.level = config.level || 'error';

  if( config.layout ) {
    layout = layouts.layout( config.layout.type, config.layout );
  }

  return sentryAppender( config.dsn, layout, config.level, config.tags );
}

exports.configure = configure;
exports.appender = sentryAppender;